package com.wwinsoft.framework.utils;

import net.sf.jxls.transformer.Configuration;
import net.sf.jxls.transformer.XLSTransformer;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wwinsoft.modules.utils.web.struts2.Struts2Utils;

/**
 * @author: Tim Chen
 * @since 1.0
 */
public class JXLTHelper {

    protected static Logger logger = LoggerFactory.getLogger(JXLTHelper.class);
    protected static String FILE_DOWNLOAD_TOKEN = "fileDownloadToken";

    public static void writeXLTtoResponse(Map beans, String templateFileName, String fileName) {
        Configuration config = new Configuration();
        XLSTransformer transformer = new XLSTransformer(config);
        InputStream inputStream = null;
        BufferedOutputStream outputStream = null;

        HttpServletResponse response = Struts2Utils.getResponse();
        response.reset();
        setDownloadToken(response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        try {
            fileName = fileName + ".xls";
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "ISO-8859-1"));
            inputStream = JXLTHelper.class.getResourceAsStream(templateFileName);
            outputStream = new BufferedOutputStream(response.getOutputStream());
            org.apache.poi.ss.usermodel.Workbook workbook = transformer.transformXLS(inputStream, beans);
            workbook.write(outputStream);
            response.flushBuffer();
        } catch (Exception e) {
            logger.error("export excel error", e);
        }
        finally {
            try {
                if (outputStream != null) outputStream.close();
                if (inputStream != null) inputStream.close();
            } catch (Exception e) {
                logger.error("close excel stream error", e);
            }
        }
    }

    private static void setDownloadToken(HttpServletResponse response){
        HttpServletRequest request =  Struts2Utils.getRequest();
        String tokenValue = request.getParameter(FILE_DOWNLOAD_TOKEN);
        if(StringUtils.isEmpty(tokenValue)){
            return;
        }
        response.addCookie(new Cookie(FILE_DOWNLOAD_TOKEN,tokenValue));
    }

}
